//
//  URLCache.m
//  TravelWithYourHeart
//
//  Created by 邹功梁 on 15/9/21.
//  Copyright (c) 2015年 邹功梁. All rights reserved.
//

#import "URLCache.h"

@implementation URLCache
#pragma mark - 删除缓存文件夹
+ (void)resetCache
{
    [[NSFileManager defaultManager] removeItemAtPath:[URLCache cacheDirectory] error:nil];
}
#pragma mark - 计算文件夹下文件的总大小
+ (float)fileSizeForDir
{
    return [URLCache fileSizeForDir:[URLCache cacheDirectory]];
}
+(float)fileSizeForDir:(NSString*)path
{
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    float size =0;
    NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
    for(int i = 0; i<[array count]; i++)
    {
        NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];
        BOOL isDir;
        if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) )
        {
            NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPath error:nil];
            size+= fileAttributeDic.fileSize/ 1024.0/1024.0;
        }
        else
        {
            [self fileSizeForDir:fullPath];
        }
    }
    return size;
}
#pragma mark - 创建缓存文件夹并返回缓存文件夹路径
+ (NSString *) cacheDirectory
{
    NSString *cachePathDirectory = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    cachePathDirectory = [cachePathDirectory stringByAppendingPathComponent:@"urlCaches"];
    return cachePathDirectory;
}
+ (NSData*) objectForKey:(NSString*)key {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];

    // 判断缓存文件夹内否存在该文件路径
    if ([fileManager fileExistsAtPath:filename])
    {
        NSData *data = [NSData dataWithContentsOfFile:filename];
        return data;
    }
    return nil;
}
#pragma mark - 存缓存
+ (void) setObject:(NSData*)data forKey:(NSString*)key
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];
    
    BOOL isDir = YES;
    if (![fileManager fileExistsAtPath:self.cacheDirectory isDirectory:&isDir]) {
        [fileManager createDirectoryAtPath:self.cacheDirectory withIntermediateDirectories:NO attributes:nil error:nil];
    }
    // 异常处理
    NSError *error;
    @try {
        // 可能出现异常的代码
        [data writeToFile:filename options:NSDataWritingAtomic error:&error];
    }
    @catch (NSException *exception) {
        // 捕获到的异常exception
    }
    @finally {
        // 结果处理
    }
}
#pragma mark - md5加密
+ (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (int)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}
#pragma mark - 删除缓存文件中的某一条缓存
+(void)removeObjectForkey:(NSString *)key
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];
    [fileManager removeItemAtPath:filename error:nil];
}
#pragma mark - 将缓存的数据转换成字典
+(NSDictionary*)returnDictionaryWithDataPath:(NSData*)data
{
    NSString *receiveStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    NSData * datas = [receiveStr dataUsingEncoding:NSUTF8StringEncoding];
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:datas options:NSJSONReadingAllowFragments error:nil];
    return dic;
}
@end
